<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>演示vue3-watch</title>
  <script src="../vue-3.0.11.js"></script>
  <style>
    a{
      display: block;
    }
    #app{
      display: flex;
      flex-direction: column;
    }
    .container{
      margin: 20px;
      border: #eeeeee solid 1px;
    }
  </style>
</head>

<body>
  <div id="app">
    <div class="container">
      <h1>watch - 监听单个属性的变化</h1>
      <input v-model="firstName1">
      <input v-model="lastName1">
      <div>{{fullName1}}</div>
    </div>

    <div class="container">
      <h1>watch</h1>
      <input v-model="name2.firstName2">
      <input v-model="name2.lastName2">
      <div>{{fullName2}}</div>
    </div>

    <div class="container">
      <h1>watch</h1>
      <input v-model="name3.firstName3">
      <input v-model="name3.lastName3">
      <div>{{name3.fullName3}}</div>
    </div>
  </div>
  <script>
    const { createApp, ref, reactive, watch } = Vue
    const firstName1 = ref('')
    const lastName1 = ref('')
    const fullName1 = ref('')



    // 监听单个属性的变化
    watch(firstName1, (oldValue, newValue)=> {
      fullName1.value = firstName1.value + lastName1.value
    })
    watch(lastName1, (oldValue, newValue)=> {
      fullName1.value = firstName1.value + lastName1.value
    })

    const fullName2 = ref('')
    const name2 = reactive({
      firstName2: '',
      lastName2: ''
    })

    // 监听对象的部分属性的变化
    watch(name2, (oldValue, newValue)=> {
      fullName2.value = name2.firstName2 + name2.lastName2
    })

    // 监听对象的部分属性的变化,返回单个对象,即监听某一个属性的变化
    watch(()=> name2.firstName2, (oldValue, newValue)=> {
      console.log(name2)
    })

    const name3 = reactive({
      firstName3: '',
      lastName3: '',
      fullName3: ''
    })

    // 这种写法会触发多次watch函数的执行
    watch(name3, (oldValue, newValue)=> {
      console.log('oldValue', oldValue);
      console.log('newValue', newValue);
      name3.fullName3 = name3.firstName3 + name3.lastName3
    })
    const app = {
      setup() {
        return {
          firstName1,
          lastName1,
          fullName1,
          name2,
          fullName2,
          name3
        }
      }
    }

    createApp(app).mount('#app')
  </script>
</body>

</html>